package com.mmall.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServiceResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.util.DateTimeUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sc on 2017/8/19.
 */

@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService iCategoryService;

    public ServiceResponse saveOrUpdateProduct(Product product) {
        if (product != null) {
            if (StringUtils.isNotBlank(product.getSubImages())) {
                String[] subImageArray = product.getSubImages().split(",");
                if (subImageArray.length > 0) {
                    product.setMainImage(subImageArray[0]);
                }
            }
            if (product.getId() != null) {
                int row = productMapper.updateByPrimaryKey(product);
                if (row > 0) {
                    return ServiceResponse.createBySuccessMessage("更新产品成功");
                }
            } else {
                int row = productMapper.insert(product);
                if (row > 0) {
                    return ServiceResponse.createBySuccessMessage("新增产品成功");
                }
            }
        }
        return ServiceResponse.createByErrorMessage("参数错误");
    }

    public ServiceResponse<String> setSaleStatus(Integer productID, Integer status) {
        if (productID == null || status == null) {
            return ServiceResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = new Product();
        product.setId(productID);
        product.setStatus(status);
        int row = productMapper.updateByPrimaryKeySelective(product);
        if (row > 0) {
            return ServiceResponse.createBySuccessMessage("修改成功");
        }
        return ServiceResponse.createByErrorMessage("修改失败");
    }

    public ServiceResponse<ProductDetailVo> manageProductDetail(Integer productid) {
        if (productid == null) {
            return ServiceResponse.createByErrorMessage("参数错误");
        }
        Product product = productMapper.selectByPrimaryKey(productid);
        if (product == null) {
            return ServiceResponse.createByErrorMessage("产品下架或删除");
        }
        //vo
        ProductDetailVo productDetailVo = assembleProductDetailInfo(product);
        return ServiceResponse.createBySuccess(productDetailVo);
    }

    private ProductDetailVo assembleProductDetailInfo(Product product) {
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(product.getId());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setMainImage(product.getMainImage());
        productDetailVo.setCategoryId(product.getCategoryId());
        productDetailVo.setSubImage(product.getSubImages());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setName(product.getName());
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setStock(product.getStock());
        productDetailVo.setSubtitle(product.getSubtitle());

        //imagehost
        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymall.com/"));

        //parentid
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null) {
            productDetailVo.setParentCategoryID(0);
        } else {
            productDetailVo.setParentCategoryID(category.getParentId());
        }
        //udpatetime
        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        //createtime
        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        return productDetailVo;

    }

    public ServiceResponse<PageInfo> getProductList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productMapper.selectList();
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product productItem : productList) {
            ProductListVo productListVo = assembleProductList(productItem);
            productListVos.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVos);
        return ServiceResponse.createBySuccess(pageInfo);
    }

    private ProductListVo assembleProductList(Product product) {
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setName(product.getName());
        productListVo.setPrice(product.getPrice());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setMainImage(product.getMainImage());
        productListVo.setStatus(product.getStatus());
        productListVo.setSubtitle(product.getSubtitle());
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymall.com/"));
        return productListVo;
    }

    public ServiceResponse<PageInfo> searchProduct(String productname, Integer productid, int pagenum, int pagesize) {
        PageHelper.startPage(pagenum, pagesize);
        List<ProductListVo> productListVos = Lists.newArrayList();
        if (StringUtils.isNotBlank(productname)) {
            productname = new StringBuilder().append("%").append(productname).append("%").toString();
        }
        List<Product> productList = productMapper.selectByNameAndProductID(productname, productid);
        for (Product productItem : productList) {
            ProductListVo productListVo = assembleProductList(productItem);
            productListVos.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVos);
        return ServiceResponse.createBySuccess(pageInfo);
    }


    //前台
    public ServiceResponse<ProductDetailVo> getProductDetail(Integer productid) {
        if (productid == null) {
            return ServiceResponse.createByErrorMessage("参数错误");
        }
        Product product = new Product();
        if (product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()) {
            return ServiceResponse.createByErrorMessage("产品下架或删除");
        }
        //vo
        ProductDetailVo productDetailVo = assembleProductDetailInfo(product);
        return ServiceResponse.createBySuccess(productDetailVo);
    }

    public ServiceResponse<PageInfo> getProductsByKeywordCategory(String keyword, Integer categoryid, int pageNum, int pageSize, String orderby) {
        if (StringUtils.isBlank(keyword) && categoryid == null) {
            return ServiceResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
        }
        List<Integer> categoryList = new ArrayList<Integer>();
        if (categoryid != null) {
            Category category = categoryMapper.selectByPrimaryKey(categoryid);
            if (category == null && StringUtils.isBlank(keyword)) {
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> productListVoList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVoList);
                return ServiceResponse.createBySuccess(pageInfo);
            }
            categoryList = iCategoryService.getCategoryAndDeepChildrenCategory(category.getId()).getData();
        }
        if (StringUtils.isNotBlank(keyword)) {
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderby)) {
            if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderby)) {
                String[] orderArray = orderby.split("_");
                PageHelper.orderBy(orderArray[0] + " " + orderArray[1]);
            }
        }
        List<Product> productList = productMapper.selectByNameAndID(StringUtils.isBlank(keyword) ? null : keyword, categoryList.size() == 0 ? null : categoryList);
        List<ProductListVo> productListVoList = Lists.newArrayList();
        for (Product item : productList) {
            ProductListVo productListVo = assembleProductList(item);
            productListVoList.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServiceResponse.createBySuccess(pageInfo);
    }
}
